package com.tskj.mh.getordertime.Interceptor.entity;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.Charset;

//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;

/**
 * @notes:
 * @program: easystar2018_ss_v2.0
 * @author: JRX
 * @create: 2019-08-13 15:00
 * 重写request 使其在后去的拦截器或方法中能获取到request的数据参数
 * 当我们用spring 拦截器实现权限校验的时候，往往我们需要从request中获取一些数据进行校验，但是当我们在拦截器获取到数据，getinputStream,
 * 那么在后续的action即：controller中我们获取不到request，这是为什么呢？
 * 因为java.util.Map所包装的HttpServletRequest对象的参数是不可改变的。 这句话的意思就是我们通过request.getInputStream.那么request就没有啦。
 **/
public class RequestToJson extends HttpServletRequestWrapper {

//    private final static Logger log = LoggerFactory.getLogger(RequestToJson.class);
    private final byte[] body;

    public RequestToJson(HttpServletRequest request) throws IOException {
        super(request);
        String sessionStream = getBodyString(request);
//        log.info("RequestToJson body:" + sessionStream);
        body = sessionStream.getBytes(Charset.forName("UTF-8"));
    }


    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body);
        ServletInputStream servletInputStream = new ServletInputStream() {
            @Override
            public int read() throws IOException {
                return byteArrayInputStream.read();
            }

            @Override
            public boolean isFinished() {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public boolean isReady() {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public void setReadListener(ReadListener listener) {
                // TODO Auto-generated method stub

            }
        };
        return servletInputStream;
    }

    //返回自己的inputStream
    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }

    /**
     * 复制input输入流
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    public InputStream cloneInputStream(ServletInputStream inputStream) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        try {
            while ((len = inputStream.read(buffer)) > -1) {
                byteArrayOutputStream.write(buffer, 0, len);
            }
            byteArrayOutputStream.flush();
        } catch (IOException e) {
//            log.info("clone servletInputStream failed", e);
            throw e;
        }
        InputStream byInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        return byInputStream;
    }

    public String getRequestToken(HttpServletRequest request) {
        String submitMehtod = request.getMethod().toUpperCase();
        //GET
        if (submitMehtod.equals("GET")) {
            try {
                String s = new String(request.getQueryString().getBytes("iso-8859-1"), "utf-8").replaceAll("%22", "\"");
                System.err.println(s);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return request.getParameter("token");
            //POST
        } else {
            JSONObject jsonObject = JSONObject.parseObject(getBodyString(request));
            if (null != jsonObject && !jsonObject.isEmpty()) {
                return jsonObject.getString("token");
            } else {
                return null;
            }

        }
    }

    //获取request中的getInputStream,返回String字段
    public String getBodyString(final ServletRequest request) {
        StringBuilder sb = new StringBuilder();
        InputStream inputStream = null;
        BufferedReader reader = null;
        try {
            inputStream = cloneInputStream(request.getInputStream());
            reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
            String line = "";
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
//            log.info("get request body code error:", e);
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }
}
